package com.tgu.service.impl;

import com.tgu.entity.model.ApproveEntity;
import com.tgu.entity.model.UsersEntity;
import com.tgu.entity.request.*;
import com.tgu.entity.response.LoginResp;
import com.tgu.mapper.ApproveDao;
import com.tgu.mapper.UsersDao;
import com.tgu.service.IUsersService;
import com.tgu.utils.result.Result;
import com.tgu.utils.result.SystemCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Service
public class UserServiceImpl implements IUsersService {

    @Autowired
    private UsersDao usersDao;
    @Autowired
    private ApproveDao approveDao;

    @Value("${system-params.website}")
    private String website;

    @Override
    public Result login(LoginReq loginReq) {
        UsersEntity user = usersDao.selectById(loginReq.getPhone());

        // 用户不存在
        if (user == null) {
            return Result.error(SystemCodeEnum.USER_NOT_EXIST);
        }

        // 密码不正确
        if (!user.getUserPassword().equals(loginReq.getPassword())) {
            return Result.error(SystemCodeEnum.PASSWORD_ERROR);
        }

        // 登录成功
        LoginResp loginResp = new LoginResp();
        loginResp.setId(user.getId());
        loginResp.setUserNickname(user.getUserNickname());
        loginResp.setUserHead(user.getUserHead());
        loginResp.setUserType(user.getUserType());
        loginResp.setUserVip(user.getUserVip());
        loginResp.setUserMoney(user.getUserMoney());
        return Result.ok(SystemCodeEnum.LOGIN_SUCCESS).setData(loginResp);
    }

    @Override
    public Result register(RegisterReq registerReq) {
        UsersEntity usersEntity = usersDao.selectById(registerReq.getPhone());
        if (usersEntity != null) {
            return Result.error(SystemCodeEnum.USER_EXISTED);
        }

        UsersEntity user = new UsersEntity();
        user.setId(registerReq.getPhone());
        user.setUserPassword(registerReq.getPassword());
        user.setInfoDate(new Date());
        user.setUserHead("head.png");

        String uuid = UUID.randomUUID().toString();  // 生出随机id
        uuid = uuid.replaceAll("-", "");  // 去掉“-”符号
        user.setUserNickname("user_" + uuid.substring(0, 15));

        int insert = usersDao.insert(user);

        if (insert < 1) {
            return Result.error(SystemCodeEnum.REGISTER_ERROR);
        }

        return Result.ok(SystemCodeEnum.REGISTER_SUCCESS);
    }

    @Override
    @Transactional
    public Result recharge(RechargeReq req) {
        UsersEntity user = usersDao.selectById(req.getUserId());
        if (user == null) {
            return Result.error(SystemCodeEnum.LOGIN_TIME_OUT);
        }

        user.setUserMoney(user.getUserMoney() + req.getMoney());

        int i = usersDao.updateById(user);
        if (i == 0) {
            return Result.error(SystemCodeEnum.RECHARGE_ERROR);
        }

        return Result.ok(SystemCodeEnum.RECHARGE_SUCCESS);
    }

    @Override
    public Result getById(String id) {
        UsersEntity user = usersDao.selectById(id);
        if (user == null) {
            return Result.error(SystemCodeEnum.USER_NOT_EXIST);
        }

        LoginResp info = new LoginResp();
        info.setId(user.getId());
        info.setUserNickname(user.getUserNickname());
        info.setUserHead(user.getUserHead());
        info.setUserType(user.getUserType());
        info.setUserVip(user.getUserVip());
        info.setUserMoney(user.getUserMoney());

        return Result.ok(SystemCodeEnum.SELECT_SUCCESS).setData(info);
    }

    @Override
    public Result changeInfo(ChangeInfoReq infoReq) {
        UsersEntity user = usersDao.selectById(infoReq.getUserId());
        if (user == null) {
            return Result.error(SystemCodeEnum.USER_NOT_EXIST);
        }

        user.setUserNickname(infoReq.getNewNickname());
        user.setUserHead(infoReq.getNewHead());
        int i = usersDao.updateById(user);
        if (i == 0) {
            return Result.error(SystemCodeEnum.USER_INFO_CHANGE_ERROR);
        }

        return Result.ok(SystemCodeEnum.USER_INFO_CHANGE_SUCCESS);
    }

    @Override
    public String upLoadApprove(HttpServletRequest req, MultipartFile file, Model m) {
        String path = null;
        //1. 接受上传的文件 @RequestParam("file") MultipartFile file
        try {
            //2.根据时间戳创建新的文件名，这样即便是第二次上传相同名称的文件，也不会把第一次的文件覆盖了
            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
            path = fileName; //保存文件名
            //3.通过req.getServletContext().getRealPath("") 获取当前项目的真实路径，然后拼接前面的文件名
            // yyc版获取路径，获取当前项目路径的上一级路径，并设置文件存放文件夹
            String property = System.getProperty("user.dir") + File.separator + "uploadApprove" + File.separator + fileName;
            //4.第一次运行的时候，这个文件所在的目录往往是不存在的，这里需要创建一下目录（创建到了webapp下uploaded文件夹下）
            File destFile = new File(property);
            destFile.mkdirs();
            //5.把浏览器上传的文件复制到希望的位置
            file.transferTo(destFile);
            //6.把文件名放在model里，以便后续显示用
            m.addAttribute("fileName", fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return website + "/portal/user/getUploadedApprove/" + path;
    }

    @Override
    public Result submitApprove(SubmitApproveReq submitApproveReq) {
        UsersEntity usersEntity = usersDao.selectById(submitApproveReq.getUserId());
        if (usersEntity == null) {
            return Result.error(SystemCodeEnum.USER_NOT_EXIST);
        }

        ApproveEntity approveEntity = new ApproveEntity();
        approveEntity.setUserId(submitApproveReq.getUserId());
        approveEntity.setInfoDate(new Date());

        String imageNames = "";
        for (int i = 0; i < submitApproveReq.getApproveImages().length; i++) {
            if (i != submitApproveReq.getApproveImages().length - 1) {
                imageNames = imageNames + submitApproveReq.getApproveImages()[i] + ",";
            } else {
                imageNames = imageNames + submitApproveReq.getApproveImages()[i];
            }
        }
        approveEntity.setImages(imageNames);

        int i = approveDao.insert(approveEntity);
        if (i == 0) {
            return Result.error(SystemCodeEnum.APPROVE_SUBMIT_ERROR);
        }

        return Result.error(SystemCodeEnum.APPROVE_SUBMIT_SUCCESS);
    }

    @Override
    public byte[] getUploadedApprove(String fileName) {
        // 拼接文件路径
        String property = System.getProperty("user.dir") + File.separator + "uploadApprove" + File.separator + fileName;
        File file = new File(property);
        FileInputStream inputStream = null;
        byte[] bytes;
        try {
            inputStream = new FileInputStream(file);
            bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        return bytes;
    }
}
